<template>
  <el-card class="box-card">
    <template #header>
      <vxe-button
        status="primary"
        class="vxe-icon-add"
        content="添加"
        @click="showAddDialog"
        v-has="'btn.Trademark.add'"
      ></vxe-button>
    </template>

    <vxe-table :data="trademarkList" border="inner" style="margin-bottom: 20px">
      <vxe-column type="seq" width="60" title="序号" align="center">
      </vxe-column>
      <vxe-column field="tmName" title="品牌名称"></vxe-column>
      <vxe-column field="logoUrl" title="品牌Logo" align="center" width="150px">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.logoUrl"
            fit="contain"
          />
        </template>
      </vxe-column>
      <vxe-column field="age" title="操作" align="center" width="150px"
        ><template #default="scope">
          <vxe-button
            status="primary"
            size="small"
            icon="vxe-icon-edit"
            @click="showUpdataDialog(scope.row)"
            v-has="'btn.Trademark.update'"
          ></vxe-button>
          <vxe-button
            status="danger"
            size="small"
            icon="vxe-icon-delete-fill"
            @click="remove(scope.row)"
            v-has="'btn.Trademark.remove'"
          ></vxe-button> </template
      ></vxe-column>
    </vxe-table>

    <el-pagination
      v-model:current-page="current"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      :small="small"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="(val: number) => getTrademarkList(1,val)"
      @current-change="(val: number) => getTrademarkList(val,pageSize)"
    />
  </el-card>

  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkForm.id ? '修改品牌' : '添加品牌'"
  >
    <!-- 设置ref的目的是为了进行表单级验证 -->
    <el-form
      ref="ruleFormRef"
      :model="trademarkForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="trademarkForm.tmName" />
      </el-form-item>
      <el-form-item label="品牌Logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="`${BASE_URL}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-icon v-if="uploadLoading" class="avatar-uploader-icon"
            ><Loading
          /></el-icon>
          <img
            v-else-if="trademarkForm.logoUrl"
            :src="trademarkForm.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <vxe-button status="primary" @click="submitForm(ruleFormRef)">
          确认
        </vxe-button>
        <vxe-button content="默认颜色" @click="resetForm(ruleFormRef)"
          >重置</vxe-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { Plus, Loading } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import {
  getTrademarkListApi,
  saveTrademarkApi,
  updateTrademarkApi,
  deleteTrademarkApi,
} from "@/api/product/trademark";

import type { FormInstance, FormRules, UploadProps } from "element-plus";
import type {
  TrademarkPageListModel,
  TrademarkModel,
  TrademarkListModel,
} from "@/types/product/trademark/trademarkModel";

const BASE_URL = import.meta.env.VITE_API_URL;

// 分页数据相关
const trademarkList = ref<TrademarkListModel>([]);
// loading
const loading = ref<boolean>(false);
// 当前页
const current = ref(1);
// 每页显示数量
const pageSize = ref(3);
// 总记录数
const total = ref(0);

// 获取品牌列表
const getTrademarkList = async (
  page = current.value,
  limit = pageSize.value
) => {
  loading.value = true;
  const result = await getTrademarkListApi(page, limit);
  trademarkList.value = result.records;
  total.value = result.total;
  current.value = page;
  pageSize.value = limit;
  loading.value = false;
  ElMessage({
    message: "获取品牌分类列表成功",
    type: "success",
  });
};

onMounted(() => {
  getTrademarkList();
});

const small = ref(false);

const dialogFormVisible = ref(false);

const ruleFormRef = ref<FormInstance>();

// 表单重置初始化
const trademarkFormInitData = () => ({
  id: undefined,
  tmName: "",
  logoUrl: "",
});

const trademarkForm = reactive<TrademarkModel>(trademarkFormInitData());

const showAddDialog = async () => {
  dialogFormVisible.value = true;
  ruleFormRef.value?.resetFields();
  Object.assign(trademarkForm, trademarkFormInitData()); // 手动进行重置
};

const showUpdataDialog = (row: TrademarkModel) => {
  dialogFormVisible.value = true;
  Object.assign(trademarkForm, row);
};

const remove = (row: TrademarkModel) => {
  ElMessageBox.confirm(`确认删除${row.tmName}吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteTrademarkApi<number>(row.id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      if (trademarkList.value.length === 1 && current.value > 1) {
        // 页面数据小于1时，页面向前减一
        current.value -= 1;
      }
      // 重新获取品牌列表
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 校验品牌名称
// 自定义校验主要是对输入值进行校验，然后利用回调进行成功或失败的处理
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.length < 2 || value.length > 10) {
    callback("长度必须在2-10个字符之间"); // 不通过给callback传递一个错误信息，是一个提示字符串
  } else {
    callback(); // 通过利用callback直接return
  }
};
// 规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { validator: validateTmName, trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "请上传品牌Logo", trigger: "blur" }],
});
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 提交表单时可能是新增也可能是修改
      if (trademarkForm.id) {
        // 修改
        await updateTrademarkApi(trademarkForm);
      } else {
        // 新增
        await saveTrademarkApi(trademarkForm.tmName, trademarkForm.logoUrl);
      }
      ElMessage.success("保存成功");
      dialogFormVisible.value = false;
      // 重新获取数据 修改则为当前页 新增则回到第一页
      getTrademarkList(trademarkForm.id ? current.value : 1);
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const uploadLoading = ref(false);

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  uploadLoading.value = false;

  trademarkForm.logoUrl = response.data;
  // 单独对这个表单元素进行校验
  ruleFormRef.value?.validateField("logoUrl");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 对文件格式和尺寸判断
  const isJPGOrPng = ["image/png", "image/jpeg"].indexOf(rawFile.type) !== -1;
  const isLt500K = rawFile.size / 1024 < 500;
  if (!isJPGOrPng) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式！");
    return false;
  }
  if (!isLt500K) {
    ElMessage.error("上传图片大小不能超过500KB!");
    return false;
  }
  uploadLoading.value = true;
  return true;
};
</script>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader :deep(.el-upload:hover) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
